package tmall.domain.controller;

import cn.dev33.satoken.stp.StpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import tmall.common.config.AppConst;
import tmall.common.dto.ResponseResult;
import tmall.common.util.ApiRet;
import tmall.common.vo.PageVO;
import tmall.domain.entity.User;
import tmall.domain.service.UserService;
import tmall.domain.vo.UserVO;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author zhangservlet
 * @date 2020/11/30
 */
@Api("用户管理")
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping("/login")
    @ApiOperation(value = "用户登录", httpMethod = "POST")
    public ResponseResult login(@RequestBody User vo) {
        User user = userService.login(vo.getUsername(), vo.getPassword());
        if (Objects.isNull(user)) {
            return ApiRet.failed("登录失败，帐号或密码错误！");
        }
        if (AppConst.USER_DISABLE.equals(user.getState())) {
            return ApiRet.failed("登录失败，该账户被禁用！");
        }
        StpUtil.login(user.getId());
        user.setPassword(null);
        return ApiRet.success(user);
    }

    @GetMapping("/logout")
    @ApiOperation(value = "用户注销登录", httpMethod = "GET")
    public ResponseResult logout() {
        StpUtil.logout();
        return ApiRet.success();
    }

    @PostMapping("/register")
    @ApiOperation(value = "用户注册", httpMethod = "POST")
    public ResponseResult register(@RequestBody UserVO vo) {
        return ApiRet.success(userService.register(vo));
    }

    @GetMapping("/emailCode")
    public ResponseResult emailCode(@RequestParam String email){
        userService.sendSecurityCode(email);
        return ApiRet.success();
    }


    @PostMapping("/list")
    @ApiOperation(value = "分页查询", httpMethod = "POST")
    public ResponseResult list(PageVO pageVO) {
        return ApiRet.success(userService.list(pageVO.getPageNum(), pageVO.getPageSize(), pageVO.getKeyWord()));
    }

    @PostMapping("/update")
    @ApiOperation(value = "修改用户信息", httpMethod = "POST")
    public ResponseResult update(User user){
        return ApiRet.success(userService.update(user));
    }


    @PostMapping("/checkDuplicate")
    @ApiOperation(value = "分页查询", httpMethod = "POST")
    public ResponseResult checkDuplicate(UserVO userVO){
        return ApiRet.success(userService.checkDuplicate(userVO));
    }
}